<?php


namespace app\api\controller\Goods;



use app\api\controller\AppController;
use app\api\controller\BaseController;
use app\api\model\Banner\BannerModel;
use app\api\model\Collage\CollageModel;
use app\api\model\Coupon\CouponModel;
use app\api\model\Goods\GoodsAttrModel;
use app\api\model\Goods\GoodsAttrValueModel;
use app\api\model\Goods\GoodsCateModel;
use app\api\model\Goods\GoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\User\UserCouponModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use think\Request;

class Goods extends AppController
{

    /**
     * @api {get} /get_goods_index 商城首页
     * @apiGroup 商品
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function index(Request $request)
    {
        $data = [];
        //商城Banner
        $data['banner_list'] = BannerModel::getBannerWhereMore([['type_id','=',3],['is_show','=',1]],"id,title,type_id,img,link_url");
        foreach ($data['banner_list'] as &$banner){
            $banner['img'] = ImageUtil::i()->replaceUrl($banner['img']);
        }
        //商城广告
        $data['advert_list'] = BannerModel::getBannerWhereMore([['type_id','=',4],['is_show','=',1]],"id,title,type_id,img,link_url");
        foreach ($data['advert_list'] as &$banner){
            $banner['img'] = ImageUtil::i()->replaceUrl($banner['img']);
        }
        //商城分类
        $data['cate_list'] = GoodsCateModel::getGoodsCateWhereMore([['is_show','=',1]],'id,cate_name,img');
        foreach ($data['cate_list'] as &$cate){
            $cate['img'] = ImageUtil::i()->replaceUrl($cate['img']);
        }

        //今日推荐
        $data['recommend_list'] = GoodsModel::getGoodsListWhere(1,6,[['g.is_recommend','=',1],['g.is_show','=',1],['g.is_del','=',0]],0,"g.id,g.mer_id,g.good_name,g.img,g.label,g.price,g.vip_price,g.cost_price,g.group_price,g.postage,g.is_bargain,g.sales,g.ficti,g.browse");
        foreach ($data['recommend_list'] as &$recommend){
            $recommend['img'] = ImageUtil::i()->replaceUrl($recommend['img']);
        }
        //猜你喜欢
        $data['like_list'] = GoodsModel::getRandomGoods(6, [['is_recommend','<>',1],['is_show','=',1],['is_del','=',0]]);
        foreach ($data['like_list'] as &$like){
            $like['img'] = ImageUtil::i()->replaceUrl($like['img']);
        }
        //特惠商品
        $data['bargain_list'] = GoodsModel::getGoodsListWhere(1,6,[['g.is_bargain','=',1],['g.is_show','=',1],['g.is_del','=',0]],0,"g.id,g.mer_id,g.good_name,g.img,g.label,g.price,g.vip_price,g.cost_price,g.group_price,g.postage,g.is_bargain,g.sales,g.ficti,g.browse,g.is_group,g.group_num");
        foreach ($data['bargain_list'] as &$bargain){
            $bargain['img'] = ImageUtil::i()->replaceUrl($bargain['img']);
        }
        return Util::returnJson(self::CODE_SUCCESS,$data);
    }

    /**
     * @api {get} /get_goods_cate_more 商品分类
     * @apiGroup 商品
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getGoodsCateMore(Request $request)
    {
        $list = [];
        $data = GoodsCateModel::getGoodsCateWhereMore([['is_show','=',1],['pid','=',0]]);
        foreach ($data as $item){
            $arr['id'] = $item['id'];
            $arr['cate_name'] = $item['cate_name'];
            $arr['img'] = ImageUtil::i()->replaceUrl($item['img']);
            array_push($list,$arr);
        }
        return Util::returnJson(self::CODE_SUCCESS,$list);
    }

    /**
     * @api {get} /get_goods_list 商品列表
     * @apiGroup 商品
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiParam {string} good_name 搜索商品名字
     * @apiParam {int} cate_id 商品分类ID
     * @apiParam {int} is_recommend 是否推荐 1：是
     * @apiParam {int} is_bargain 特惠商品 1：是
     * @apiParam {int} is_composite 综合排序  1 ， 0
     * @apiParam {int} is_price 价格排序 (1价格升序 2价格降序)
     * @apiParam {int} is_sales 销量排序 (1销量升序 2销量降序)
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getGoodsList(Request $request)
    {
        $param = $request->param();
        $where = [
            ['is_show', '=', 1],
            ['is_del', '=', 0]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $good_name = !empty($param['good_name']) ? $param['good_name'] : "";
        //分类
        $cate_id = !empty($param['cate_id']) ? $param['cate_id'] : 0;
        //推荐
        $is_recommend = !empty($param['is_recommend']) ? $param['is_recommend'] : 0;
        //特惠商品
        $is_bargain = !empty($param['is_bargain']) ? $param['is_bargain'] : 0;
        if (!empty($good_name)) {
            array_push($where, ['g.good_name', 'like', '%' . $good_name . '%']);
        }
        if(!empty($is_recommend)){
            array_push($where, ['g.is_recommend', '=', $is_recommend]);
        }
        if(!empty($is_bargain)){
            array_push($where, ['g.is_bargain', '=', $is_bargain]);
            array_push($where, ['g.is_group', '=', 1]);
        }
        if(!empty($cate_id)){
            array_push($where, ['gcr.cate_id', '=', $cate_id]);
        }

        //综合
        $sort['is_composite'] = !empty($param['is_composite']) ? 1 : 0;
        //价格 (1价格升序 2价格降序)
        $sort['is_price'] = !empty($param['is_price']) ? $param['is_price'] : "";
        //销量(1销量升序 2销量降序)
        $sort['is_sales'] = !empty($param['is_sales']) ? $param['is_sales'] : "";
        $list = GoodsModel::getGoodsListWhere($page, $limit, $where, $sort,'g.id,g.good_name,g.label,g.img,g.slider_img,g.brief,g.price,g.vip_price,g.group_price,g.group_num,g.is_postage,g.postage,g.is_hot,g.is_new,g.is_benefit,g.is_recommend,g.details,g.sales,g.ficti,g.browse');
        $count = GoodsModel::getGoodsCountWhere($where);
        foreach ($list as &$item){
            $item['label'] = json_decode($item['label'],true);
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {get} /get_goods_like_list 猜你喜欢
     * @apiGroup 商品
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getGoodsLikeList(Request $request)
    {
        $where = [
            ['is_recommend','<>',1],
            ['is_show', '=', 1],
            ['is_del', '=', 0]
        ];
        $list = GoodsModel::getRandomGoods(6, $where);
        foreach ($list as &$item){
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            /*$images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";*/
        }
        return Util::returnJson(self::CODE_SUCCESS, $list);
    }

    /**
     * @api {get} /get_goods_info 商品详情
     * @apiGroup 商品
     * @apiParam {int} id 商品ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getGoodsInfo(Request $request)
    {
        $param = $request->param();
        $goods = GoodsModel::getGoodsWhere([['id','=',$param['id']]],'');
        $goods['img'] = ImageUtil::i()->replaceUrl($goods['img']);
        $goods['label'] = json_decode($goods['label'],true);
        $images = !empty($goods['slider_img']) ? json_decode($goods['slider_img'],true) : [];
        foreach ($images as &$image){
            $image = ImageUtil::i()->replaceUrl($image);
        }
        $goods['slider_img'] = $images;
        $goods['details'] = !empty($goods['details']) ? htmlspecialchars_decode($goods['details']) : "";

        if(!empty($goods['sales_setting'])){
            $sales_setting = json_decode($goods['sales_setting'],true);
            $goods['level'] = $sales_setting['level'];
            $goods['level_sales0'] = $sales_setting['level_sales0'];
            $goods['level_sales1'] = $sales_setting['level_sales1'];
            $goods['level_sales2'] = $sales_setting['level_sales2'];
        }else{
            $goods['level'] = 0;
            $goods['level_sales0'] = 0;
            $goods['level_sales1'] = 0;
            $goods['level_sales2'] = 0;
        }

        $attr = GoodsAttrModel::getGoodsAttrWhereMore([['goods_id','=',$goods['id']]]);
        if(!empty($attr)){
            foreach ($attr as &$it){
                $it['attr_values'] = explode(",",$it['attr_values']);
            }
            $goods['attr'] = $attr;
            $goods['attr_value'] = GoodsAttrValueModel::getGoodsAttrValueWhereMore([['goods_id','=',$goods['id']]]);
            //组装数据
            foreach ($goods['attr_value'] as &$item){
                $suk = explode(",",$item['suk']);
                foreach ($attr as $k=>$val){
                    $item[$val['attr_name']] = $suk[$k];
                }
            }
        }else{
            $goods['attr'] = [];
            $goods['attr_value'] = [];
        }

        //特惠商品查看开团
        if(!empty($goods['is_bargain']) && !empty($goods['is_group'])){
            $c_field = ['c.*,u.head_img,u.nickname'];
            $collages = CollageModel::getCollageListWhereMore([['c.goods_id','=',$goods['id']],['c.status','=',0]],$c_field);
            $data = [];
            if(!empty($collages)){
                foreach ($collages as &$collage){
                    //$users = OrderModel::getOrderListWhereMore([['o.collage_id','=',$collage['id']],['o.uid','<>',$collage['uid']]],'u.head_img,u.nickname');
                    $users = OrderModel::getOrderListWhereMore([['o.collage_id','=',$collage['id']]],'u.head_img,u.nickname');
                    foreach ($users as &$user){
                        $user['head_img'] = ImageUtil::i()->replaceUrl($user['head_img']);
                    }
                    unset($user);
                    $collage['users'] = $users;
                    $collage['head_img'] = ImageUtil::i()->replaceUrl($collage['head_img']);
                    array_push($data,$collage);
                }
            }
            $goods['collages'] = $data;

            //订单===拼团总量(待完成+已完成)+已拼团(完成的)
            $where_1 = [
                ['is_group','=',1],
                ['status','=',1]
            ];
            $where_2 = [
                ['is_group','=',1],
                ['status','=',2]
            ];
            $where_3 = [
                ['is_group','=',1],
                ['status','=',3]
            ];
            $goods['order_all'] = OrderModel::getOrderListWhereOrCount([$where_1,$where_2,$where_3]);
            $goods['order_finish'] = OrderModel::getOrderListWhereCount([['is_group','=',1],['status','=',3]]);

        }

        //客服
        if(!empty($this->setting)){
            $sys_extend = json_decode($this->setting['sys_extend'],true);
            $goods['contact_way'] = $sys_extend['contact_way'];
        }else{
            $goods['contact_way'] = "";
        }

        //获取相关课程优惠券
        $cou_where = [
            ['label','=',2],
            ['is_show','=',1],
            ['goods_ids','like','%'.$goods['id'].','.'%'],
            ['start_time','<',date("Y-m-d H:i:s",time())],
            ['end_time','>',date("Y-m-d H:i:s",time())]
        ];
        $cou_where_1 = [
            ['label','=',2],
            ['is_show','=',1],
            ['type','=',1],
            ['start_time','<',date("Y-m-d H:i:s",time())],
            ['end_time','>',date("Y-m-d H:i:s",time())]
        ];
        $coupon_list = CouponModel::getCouponWhereOrMore([$cou_where,$cou_where_1],'id,coupon_title,is_level,label,mer_id,attr,type,goods_ids,amount,total_amount,is_infinite,total_num,receive_num,start_time,end_time');
        $goods['coupon_list'] = !empty($coupon_list) ? $coupon_list : [];
        foreach ($goods['coupon_list'] as &$item){
            if(!empty($this->user)){
                $count = UserCouponModel::getUserCouponCountWhere([['uid','=',$this->user['id']],['coupon_id','=',$item['id']]]);
                if($count){
                    //用户已领取
                    $item['is_user'] = 1;
                }else{
                    $item['is_user'] = 0;
                }
            }else{
                $item['is_user'] = 0;
            }
        }
        unset($item);

        return Util::returnJson(self::CODE_SUCCESS, $goods, "");
    }

}
